<script>
import {
  copyProject,
  deleteProject, downloadConfigJSON,
  getAimetaProjectList
} from "@/api/aihuman/IntelligentInteraction/IntelligentInteraction";
import AddProject from "@/views/aihuman/IntelligentInteraction/addProject/addProject.vue";
import ReleaseDialog from "@/views/aihuman/IntelligentInteraction/addProject/ReleaseDialog.vue";
import ConfigDialog from "@/views/aihuman/IntelligentInteraction/addProject/configDialog.vue"; // 引入 configDialog 组件
import {mapGetters} from "vuex";
import {getUrl} from "@/util/aihuman/getUrl";
import ReleaseDialogTemp from "@/views/aihuman/IntelligentInteraction/addProject/ReleaseDialogTemp.vue";

export default {
  name: "RecentProjects",
  components: {ReleaseDialogTemp, ReleaseDialog, AddProject, ConfigDialog}, // 添加 ConfigDialog 组件
  data() {
    return {
      activeName: '2',
      projectList: []
    }
  },
  created() {
    this.getList()
  },
  filters: {
    formatDate(val) {
      if (!val) {
        return ''
      }
      let date = new Date(val)
      const year = date.getFullYear();
      const month = String(date.getMonth() + 1).padStart(2, '0'); // 月份从0开始，需加1
      const day = String(date.getDate()).padStart(2, '0');
      const hours = String(date.getHours()).padStart(2, '0');
      const minutes = String(date.getMinutes()).padStart(2, '0');
      const seconds = String(date.getSeconds()).padStart(2, '0');

      return `${year}-${month}-${day}`;
    }
  },
  computed: {
    ...mapGetters(['permission']),
    permissionList() {
      return {
        addBtn: this.vaildData(this.permission[`board-add`], false),
        creationUse: this.vaildData(this.permission[`creation-use`], false),
        creationDelete: this.vaildData(this.permission['creation-delete'], false),
        creationEdit: this.vaildData(this.permission['creation-edit'], false),
      }
    }
  },
  methods: {
    buildConfig(item) {
      downloadConfigJSON({id: item.id}).then(res => {
        this.$message.success('生成成功')
      })
    },
    getUrl,
    copyProject(item) {
      let str = item.projectName + '_副本'
      if (str.length > 30) {
        this.$message.error('复制失败：项目名称超出30个字符')
        return false
      }
      copyProject({id: item.id, projectName: item.projectName + '_副本'}).then(res => {
        this.$message.success(res.data.msg)
        this.getList()
      })
    },
    removeProject(item) {
      this.$confirm('删除项目无法找回，确定删除吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deleteProject({id: item.id}).then(res => {
          this.$message({
            type: 'success',
            message: res.data.msg
          })
          this.getList()
        });
      }).catch(() => {

      });
    },
    toPage() {
      if (this.activeName === '2') {
        this.$router.push('/aihuman/IntelligentInteraction/index')
      } else {
        console.log('1')
      }
    },

    handleTab({name}) {
      this.getList()
    },
    newProject() {
      if (this.activeName === '1') {

      } else {
        this.$refs.addRef.open({}, 'add')
      }
    },
    openEdit(item) {
      let a = document.createElement('a')
      a.target = '_blank'
      a.href = this.getUrl() + '/aihuman/aihumanEdit/aiHumanAsset/' + item.id
      a.click()

      console.log(a);
    },
    preview(item) {
      this.$refs.addRef.open(item, 'preview')
    },
    editItem(item) {
      this.$refs.addRef.open(item, 'edit')
    },
    release(item) {
      this.$refs.releaseDialogTemp.open(item)

      // if (item.applyType === 1) {
      //   this.openConfigDialog(item)
      // } else {
      //   this.$refs.releaseDialog.open(item)
      // }
    },
    async getList() {
      const params = {
        projectType: this.activeName,
        pageNo: 1,
        pageSize: this.permissionList.addBtn ? 3 : 4
      }
      const {data} = await getAimetaProjectList(params)
      this.projectList = data.data.records
    },
    openView(item) {
      if (item.robotInstanceId !== '') {
        let a = document.createElement('a')
        a.target = '_blank'
        a.href = this.getUrl() + '/aihuman/aihumanShow/index.html?id=' + item.id
        a.click()
      } else {
        let a = document.createElement('a')
        a.target = '_blank'
        a.href = this.getUrl() + '/aihuman/aihumanEdit/aiHumanAsset/' + item.id
        a.click()
      }
    },
    isAbsolutePath(path) {
      if (!path) return ''

      let reg = path.includes('https://')
      if (reg) {
        return path
      } else {
        return `${this.getUrl()}${path}`
      }
    },
    openConfigDialog(item) { // 定义打开 configDialog 的方法
      this.$refs.configDialog.open(item);
    }
  }
}
</script>

<template>
  <div>
    <div class="board-header__title">最近项目</div>

    <div class="recent-header">
      <el-tabs v-model="activeName" @tab-click="handleTab">
        <!--        <el-tab-pane label="数字解说员" name="1"></el-tab-pane>-->
        <el-tab-pane label="智能交互" name="2"></el-tab-pane>
      </el-tabs>

      <div class="recent-header__more">
        <el-button type="text" @click="toPage">查看更多></el-button>
      </div>
    </div>

    <div class="project-items__board">
      <div v-if="permissionList.addBtn" class="project-create" @click="newProject">
        <div class="icon el-icon-plus"></div>
        <div>快速创建</div>
      </div>

      <div class="project-box" v-for="item in projectList" :key="item.id">
        <div class="project-img"
             :style="{background: `url(${isAbsolutePath(item.backgroundImage)}) no-repeat center center`,backgroundSize: 'cover'}">
          <div class="project-model">
            <el-button type="primary" style="background: #318DEE; border-color: #318DEE;" @click="openView(item)">
              {{ item.robotInstanceId === '' ? '去配置' : '问答预览' }}
            </el-button>
          </div>
          <div class="project-img-tags">
            <img v-if="item.applyType === 2" src="~@/assets/aihuman/diannao.png" alt="">
            <img v-if="item.applyType === 1" src="~@/assets/aihuman/yitiji.png" alt="">
            <img v-if="item.applyType === 3" src="~@/assets/aihuman/shouji.png" alt="">
          </div>
          <img :src="`${getUrl()}`+item.previewImageUrl" alt="">
        </div>

        <div class="project-title">
          <div class="project-title__box" :title="item.projectName">
            <strong>{{ item.projectName }}</strong>
            <button v-if="permissionList.creationEdit" class="edit-ico" @click="editItem(item)">
              <img src="@/assets/aihuman/edit.png" alt="">
            </button>
          </div>

        </div>
        <div class="date-text">
          <span>{{ item.dimensionType === 3 ? 'Web3D' : item.dimensionType === 2 ? '2D' : 'UE3D' }}</span>
          <span> | </span>
          <span>{{ item.createTime | formatDate }}</span>
        </div>

        <div class="button-block">
          <button v-if="permissionList.creationUse" class="edit-btn active" @click="release(item)">发布与使用</button>
          <button v-if="permissionList.creationEdit" class="edit-btn" @click="openEdit(item)">编辑项目</button>

          <el-dropdown>
            <button class="edit-btn"><span class="el-icon-more"></span>
            </button>
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item @click.native="preview(item)">基本信息</el-dropdown-item>
              <el-dropdown-item v-if="permissionList.creationEdit" @click.native="copyProject(item)">复制项目
              </el-dropdown-item>
              <el-dropdown-item v-if="permissionList.creationDelete" @click.native="removeProject(item)">删除项目
              </el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
        </div>
      </div>
    </div>

    <add-project
      ref="addRef"
      @save="getList"
    />

    <release-dialog
      ref="releaseDialog"
    />

    <config-dialog
      ref="configDialog"
    /> <!-- 添加 configDialog 组件 -->

    <release-dialog-temp
      ref="releaseDialogTemp"
    />
  </div>
</template>

<style scoped lang="scss">
@import "~@/styles/aihuman/img-list";

.board-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 46px;

  &__title {
    font-weight: normal;
    font-size: 18px;
    margin-bottom: 8px;
  }

  /deep/ .el-button {
    background: #fff;

    &:hover {
      background: #0e5ef7;
      color: #fff;
    }
  }
}

</style>
